package cn.com.anypay.manager.config;

import cn.com.anypay.manager.miaoma.sysuser.SysUserService;
import cn.dev33.satoken.dao.SaTokenDao;
import cn.dev33.satoken.dao.SaTokenDaoDefaultImpl;
import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpInterface;
import cn.dev33.satoken.stp.StpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Collections;
import java.util.List;

/**
 * Sa-Token 配置类
 */
@Slf4j
@Configuration
public class SaTokenConfig implements WebMvcConfigurer {
    
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new SaInterceptor(handle -> {
            // 关键日志，彻查 token 传递
            ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attrs != null) {
                String method = attrs.getRequest().getMethod();
                String tokenName = StpUtil.getTokenName();
                String authHeader = attrs.getRequest().getHeader("Authorization");
                
                // 跳过OPTIONS预检请求
                if ("OPTIONS".equals(method)) {
                    System.out.println("跳过OPTIONS预检请求");
                    return;
                }
            } else {
                System.out.println("=== Sa-Token 拦截器执行，但未获取到ServletRequestAttributes ===");
            }
            SaRouter.match("/**")
                .notMatch("/api/auth/login")
                .notMatch("/api/auth/logout")
                .notMatch("/api/auth/sms/send")
                .notMatch("/api/auth/sms/verify")
                .notMatch("/api/auth/email/send")
                .notMatch("/api/auth/email/verify")
                .notMatch("/api/anon/**")
                .notMatch("/doc.html")
                .notMatch("/swagger-ui/**")
                .notMatch("/swagger-resources/**")
                .notMatch("/v3/api-docs/**")
                .notMatch("/webjars/**")
                .notMatch("/favicon.ico")
                .notMatch("/error")
                .check(r -> {
                    // 添加详细的token检查日志
                    String currentToken = StpUtil.getTokenValue();
                    System.out.println("当前请求token: " + currentToken);
                    if (currentToken == null || currentToken.isEmpty()) {
                        System.out.println("错误：未能获取到token值");
                        throw new cn.dev33.satoken.exception.NotLoginException("未能读取到有效 token", "", "");
                    }
                    StpUtil.checkLogin();
                });
        })).addPathPatterns("/**");
    }
    
    /**
     * 获取token的方式配置
     */
    @Autowired
    private SysUserService sysUserService;
    
    @Bean
    @Primary
    public StpInterface getStpInterface() {
        return new StpInterface() {
            @Override
            public List<String> getPermissionList(Object loginId, String loginType) {
                try {
                    // 返回此loginId拥有的权限列表
                    Long userId = Long.valueOf(loginId.toString());
                    return sysUserService.getUserPermissions(userId);
                } catch (Exception e) {
                    log.error("获取用户权限失败: loginId={}, error={}", loginId, e.getMessage());
                    return Collections.emptyList();
                }
            }

            @Override
            public List<String> getRoleList(Object loginId, String loginType) {
                try {
                    // 返回此loginId拥有的角色列表
                    Long userId = Long.valueOf(loginId.toString());
                    return sysUserService.getUserRoleCodes(userId);
                } catch (Exception e) {
                    log.error("获取用户角色失败: loginId={}, error={}", loginId, e.getMessage());
                    return Collections.emptyList();
                }
            }
        };
    }
}